import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Solution1584 {
    public int minCostConnectPoints(int[][] points) {
        int n=points.length;
        int[] b=new int[n];
        for (int i=0;i<n;i++){
            b[i]=i;
        }
        List<int[]> list=new ArrayList<>();
        for (int i=0;i<n;i++){
            for (int j=i+1;j<n;j++){
                list.add(new int[]{i,j,Math.abs(points[i][0]-points[j][0])+Math.abs(points[i][1]-points[j][1])});
            }
        }
        list.sort(Comparator.comparingInt(a -> a[2]));
        int t=0;
        int ans=0;
        for (int[] ints : list) {
            int x=find(b,ints[0]);
            int y=find(b,ints[1]);
            if (x!=y){
                t++;
                ans=ans+ints[2];
                b[x]=y;
            }
            if (t==n-1){
                break;
            }
        }
        return ans;
    }

    int find(int[] b,int k){
        List<Integer> list=new ArrayList<>();
        while (k!=b[k]){
            list.add(k);
            k=b[k];
        }
        for (Integer integer : list) {
            b[integer]=k;
        }
        return k;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1584().minCostConnectPoints(new int[][]{{0,0},{2,2},{3,10},{5,2},{7,0}}));
    }
}
